package com.vlad.domen.waiters;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.vlad.domen.Restaurant;
import com.vlad.domen.util.Order;
import com.vlad.domen.util.Status;

public class WaiterTeam {
	private final List<Waiter> waiters;
	private final ExecutorService waiterExecutor = Executors
			.newFixedThreadPool(10);
	private final Queue<Order> orders = new LinkedList<Order>();

	public List<Waiter> getWaiters() {
		return waiters;
	}

	public WaiterTeam(int waiterCount, Restaurant restaurant) {
		waiters = new ArrayList<Waiter>(waiterCount);
		for (int i = 0; i < waiterCount; i++) {
			waiters.add(new Waiter(i, restaurant));
		}
	}

	public Queue<Order> getOrders() {
		return orders;
	}

	public void startWork() {
		for (Waiter waiter : waiters) {
			waiterExecutor.execute(waiter);
		}
	}

	public synchronized void takeOrder(Order order) {
		orders.offer(order);
		for (Waiter waiter : waiters) {
			synchronized (waiter) {
				if (waiter.getStatus() == Status.IDLE) {
					waiter.notify();
					break;
				}
			}
		}
	}

	public void stop() {
		waiterExecutor.shutdownNow();
	}

}
